'use client'

import { useState } from 'react'
import { Star } from 'lucide-react'

// 获取星星样式的辅助函数
function getStarStyle(starNumber: number, rating: number): string {
  if (starNumber <= rating) {
    // 完全填充的星星
    return 'fill-yellow-400 text-yellow-400'
  } else if (starNumber - 1 < rating && rating < starNumber) {
    // 部分填充的星星（半星效果）
    const fraction = rating - (starNumber - 1)
    if (fraction >= 0.5) {
      return 'fill-yellow-400 text-yellow-400'
    } else {
      return 'fill-yellow-200 text-yellow-400'
    }
  } else {
    // 空星星
    return 'fill-gray-200 text-gray-200'
  }
}

interface StarRatingProps {
  rating: number
  onRatingChange?: (rating: number) => void
  readonly?: boolean
  size?: 'sm' | 'md' | 'lg'
  showValue?: boolean
}

export function StarRating({ 
  rating, 
  onRatingChange, 
  readonly = false, 
  size = 'md',
  showValue = false 
}: StarRatingProps) {
  const [hoverRating, setHoverRating] = useState(0)

  const sizeClasses = {
    sm: 'h-4 w-4',
    md: 'h-5 w-5',
    lg: 'h-6 w-6'
  }

  const handleClick = (value: number) => {
    if (!readonly && onRatingChange) {
      onRatingChange(value)
    }
  }

  const handleMouseEnter = (value: number) => {
    if (!readonly) {
      setHoverRating(value)
    }
  }

  const handleMouseLeave = () => {
    if (!readonly) {
      setHoverRating(0)
    }
  }

  const displayRating = hoverRating || rating

  return (
    <div className="flex items-center gap-1">
      <div className="flex items-center">
        {[1, 2, 3, 4, 5].map((star) => (
          <button
            key={star}
            type="button"
            className={`${
              readonly ? 'cursor-default' : 'cursor-pointer hover:scale-110'
            } transition-transform duration-150`}
            onClick={() => handleClick(star)}
            onMouseEnter={() => handleMouseEnter(star)}
            onMouseLeave={handleMouseLeave}
            disabled={readonly}
          >
            <Star
              className={`${sizeClasses[size]} ${
                getStarStyle(star, displayRating)
              } transition-colors duration-150`}
            />
          </button>
        ))}
      </div>
      
      {showValue && (
        <span className="text-sm text-gray-600 ml-2">
          {rating.toFixed(1)}
        </span>
      )}
    </div>
  )
}

// 只显示评分的组件
export function StarDisplay({ rating, size = 'sm', showValue = true }: {
  rating: number
  size?: 'sm' | 'md' | 'lg'
  showValue?: boolean
}) {
  return (
    <StarRating 
      rating={rating} 
      readonly 
      size={size} 
      showValue={showValue}
    />
  )
}
